let curUnionID = null;

function fixData(dataArr) {

    let arr = [];
    for (let i = 0; i < dataArr.length; ++i) {
        let newData = {};
        let data = dataArr[i];
        for (let key in data) {
            if (key === 'unionInfo') continue;
            if (data.hasOwnProperty(key)) {
                newData[key] = data[key];
            }
        }
        let unionInfo = data.unionInfo.find(function (e) {
            return e.unionID == curUnionID;
        });
        if (!!unionInfo) {
            for (let key in unionInfo) {
                if (unionInfo.hasOwnProperty(key)) {
                    newData[key] = unionInfo[key];
                }
            }
        }
        arr.push(newData);
    }
    return arr;
}

function showUserType(uid, type = 0) {
    $("#userUid").val(uid);
    $("#userType").val(type)
    $('#editUserType').modal('show');
}

function editType() {

    let uid = $("#userUid").val();
    let type = $("#userType").val() || 0;
    apiUpdateUserDataEx({ uid: uid, "unionInfo.unionID": curUnionID }, { "unionInfo.$.userType": type }, function () {
        $('#editUserType').modal('hide');
        $.modal({ body: '操作成功' });
        var currentPage = $('#userList').bootstrapTable('getOptions').pageNumber
        createList(currentPage);
    });
}


function createList(pageNo = 1, pageSize = 10) {

    let matchData = {
        'isRobot': {
            $ne: true
        }
    };
    let uid = $("#txtSearch").val();
    if (!!uid) {
        matchData.uid = parseInt(uid || "");
    }

    let isOnLine = $("#onLineUser").val();
    if (isOnLine != '0') {
        matchData.unionInfo = {
            $elemMatch: {
                userType: isOnLine,
                unionID: curUnionID,
            }
        }
    } else {
        matchData.unionInfo = {
            $elemMatch: {
                unionID: curUnionID,
            }
        }
    }

    var start = (pageNo - 1) * pageSize;
    apiAdminGetRecord("userModel", start, pageSize, matchData, function (data) {
        if (data.code === 0) {
            if (data.code === 0) {
                setTimeout(() => {
                    let recordArr = fixData(data.msg.recordArr);
                    data.msg.recordArr = recordArr;
                    $('#dataList').bootstrapTable('load', data.msg);
                }, 200)
            }
        }
    });
}


$(document).ready(function () {
    // 初始化数据列名

    var parameters = parseQueryString(window.location.href);
    curUnionID = parameters.unionID;

    //数据表格初始化
    $('#dataList').bootstrapTable({
        showRefresh: true,
        striped: true, // 是否显示行间隔色
        pageNumber: 1, // 初始化加载第一页
        pagination: true, // 是否分页
        sidePagination: 'server', // server:服务器端分页|client：前端分页
        pageSize: 10, // 单页记录数
        pageList: [10, 20, 30],
        theadClasses: "thead-light", //这里设置表头样式
        totalField: "totalCount",
        smartDisplay: false,
        dataField: "recordArr",
        maintainSelected: true,
        buttonsClass: 'light',
        buttonsPrefix: 'btn',
        showRefresh: false, // 刷新按钮
        onPageChange: function (number, size) {
            createList(number, size);
        },
        queryParams: function (params) { // 上传服务器的参数
            var temp = { //如果是在服务器端实现分页，limit、offset这两个参数是必须的
                limit: params.limit, // 每页显示数量
                offset: params.offset, // SQL语句起始索引
            };
            return temp;
        },
        onPostBody: function () {
            //重新启用弹出层,否则formatter格式化函数返回的html字符串上的tooltip提示不生效
            $('[data-bs-toggle="tooltip"]').each(function (i, el) {
                new bootstrap.Tooltip(el)
            })
        },
        onLoadSuccess: function () {
            //重新启用弹出层,否则formatter格式化函数返回的html字符串上的tooltip提示不生效
            $('[data-bs-toggle="tooltip"]').each(function (i, el) {
                new bootstrap.Tooltip(el)
            })
        },
        queryParams: function (params) { // 上传服务器的参数
            var temp = { //如果是在服务器端实现分页，limit、offset这两个参数是必须的
                limit: params.limit, // 每页显示数量
                offset: params.offset, // SQL语句起始索引
            };
            return temp;
        },
        columns: [{
            title: 'id',
            field: '_id',
            visible: false
        },
        {
            title: '用户ID',
            width: 100,
            align: "center",
            valign: "middle",
            field: 'uid',
        }, {
            title: '昵称',
            width: 100,
            align: "center",
            valign: "middle",
            field: 'nickname',
        },
        {
            title: '头像',
            width: 100,
            align: "center",
            valign: "middle",
            field: 'avatar',
            formatter: avaterImg
        },
        {
            title: '联盟ID',
            width: 100,
            align: "center",
            valign: "middle",
            field: 'unionID',
            sortable: true,
            order: "asc",

        },
        {
            title: '上级ID',
            width: 150,
            align: "center",
            valign: "middle",
            field: 'spreaderID',
        },
        // {
        //     title: '分数',
        //     width: 150,
        //     align: "center",
        //     valign: "middle",
        //     field: 'score',
        //     formatter: scoreMatter,
        // },
        //  {
        //     title: '保险柜分数',
        //     width: 150,
        //     align: "center",
        //     valign: "middle",
        //     field: 'safeScore',
        // }, 
        // {
        //     title: '点位',
        //     width: 100,
        //     align: "center",
        //     valign: "middle",
        //     field: 'rebateRate',
        //     formatter: function (value) {
        //         return (value * 100) + '%';
        //     },
        // }, 
        {
            title: '黑白名单',
            width: 100,
            align: "center",
            valign: "middle",
            field: 'userType',
            formatter: function (value) {
                var htm = "";
                if (!!value) {
                    if (value == 1) {
                        htm = `<span class="badge rounded-pill text-bg-dark">黑名单</span>`;
                    } else if (value == 2) {
                        htm = `<span class="badge rounded-pill text-bg-success text-white ">白名单</span>`;
                    }
                } else {
                    //  htm = `<span class="badge rounded-pill text-bg-success">正常</span>`;
                }
                return htm;
            }
        },
        {
            title: '加入时间',
            width: 150,
            align: "center",
            valign: "middle",
            field: 'joinTime',
            formatter: dateMatter
        },
        {
            title: '操作',
            width: 100,
            align: "center",
            valign: "middle",
            formatter: option
        }
        ]
    });
    createList(1);
    $('#dataList').bootstrapTable('hideLoading');
});

function dateMatter(value, row, index) {
    return new Date(value).toLocaleString();
}

function scoreMatter(value, row, index) {
    return value ? value.toFixed(2) : 0;
}


// 定义删除、更新按钮
function option(value, row, index) {
    var htm = "";
    htm += `<button type = "button" class="btn btn-light" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="设置黑白名单" onClick = 'showUserType(${row.uid}, ${row.userType})' ><i class="bi bi-person-fill-gear fs-5 text-success"></i></button > `;
    htm += `  <button type="button" class="btn btn-light"  data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="战绩明细" onClick="unionScore(${row.uid})"><i class="bi bi-clipboard-data-fill fs-5 text-success"></i></button>`;
    //htm += `  <button type="button" class="btn btn-light"  data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="战绩奖励" onClick="unionTarget(${row.uid})"><i class="bi bi-award-fill fs-5 text-success"></i></button>`;
    return htm;
}


function unionScore(uid) {

    window.rolemodal = $.modal({
        url: `unionUserScoreChange.html?unionID=${curUnionID}&uid=${uid}`,
        title: '战绩明细',
        buttons: [],
        modalDialogClass: 'modal-dialog-centered modal-xl',
    })
}

function unionTarget(uid) {

    window.rolemodal = $.modal({
        url: `unionTarget.html?unionID=${curUnionID}&uid=${uid}`,
        title: '战绩奖励',
        buttons: [],
        modalDialogClass: 'modal-dialog-centered modal-xl',
    })
}



function avaterImg(value, row, index) {
    var htm = "";
    htm = `<img  style="width: 40px ; height: 40px;"  src="${value}" class="img-thumbnail" >`;
    return htm;
}